package com.yiwenup.leetcode.site;

import java.util.HashMap;

/**
 * https://leetcode-cn.com/problems/two-sum/
 */
public class No001 {
    public int[] twoSum1(int[] nums, int target) {
        if (nums.length == 2) {
            return new int[]{0, 1};
        }

        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

    public int[] twoSum2(int[] nums, int target) {
        if (nums.length == 2) {
            return new int[]{0, 1};
        }

        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(nums[0], 0);
        for (int i = 1; i < nums.length; i++) {
            int key = target - nums[i];
            if (map.containsKey(key)) {
                return new int[]{map.get(key), i};
            } else {
                map.put(nums[i], i);
            }
        }

        return new int[0];
    }
}
